package com.kotei;

import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import net.lingala.zip4j.ZipFile;
import net.lingala.zip4j.exception.ZipException;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class UnZipAndCopy {
    public static void main(String[] args) throws IOException {
        String zipDir = "D:\\nfzg\\datasyncSD\\37send\\20250528";
        File file = new File(zipDir);
        File[] files = file.listFiles((dir, name) -> name.endsWith(".zip"));

        for (int i = 0; i < files.length; i++) {
            File file1 = files[i];
            String zipName = file1.getName();
            String code = zipName.substring(0, 2);
            String password = getPassword(code);

            extractWithPassword(file1.getAbsolutePath(), zipDir, password);
            String fileDir = file1.getAbsolutePath().replace(".zip", "");

            // 确定是目录
            boolean directory = new File(fileDir).isDirectory();
            if (directory) {
                FileUtil.copy(new File(fileDir + "\\" + code + "0000"), new File(zipDir + "\\" + "tiqv"), true);
            }
        }
    }


    public static String getPassword(String code) throws IOException {
        // 使用相对路径（相对于当前类所在的包）
        InputStream inputStream = UnZipAndCopy.class.getResourceAsStream("/key.json");

        // 注意路径前的"/"表示从classpath根目录开始
        if (inputStream != null) {
            byte[] bytes = inputStream.readAllBytes();
            String content = new String(bytes);
            // 解析JSON数组
            JSONArray jsonArray = new JSONArray(content);
            for (int i = 0; i < jsonArray.size(); i++) {
                if (code.equals(JSONUtil.parseObj(jsonArray.get(i).toString()).get("code").toString())) {
                    return JSONUtil.parseObj(jsonArray.get(i).toString()).get("zipPassword").toString();
                }
            }
        }
        return null;
    }


    public static void extractWithPassword(String zipPath, String destDir, String password) {
        try {
            ZipFile zipFile = new ZipFile(zipPath);
            if (zipFile.isEncrypted()) {
                zipFile.setPassword(password.toCharArray());
            }
            zipFile.extractAll(destDir);
            System.out.println("解压成功！");
        } catch (RuntimeException | ZipException e) {
            if (e.getMessage().contains("password")) {
                System.err.println("密码错误或未提供密码");
            } else {
                e.printStackTrace();
            }
        }
    }
}
